package com.example.live.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.SweepGradient
import android.graphics.Typeface
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.example.common.view.CircleCountDownView
import java.text.SimpleDateFormat
import java.util.*
//自定义圆形倒计时试图
class RedCircleCountDownView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet ?= null, defStyle : Int = 0):View(context,attributeSet,defStyle){
    // 进度条背景默认为半透明黑色
    private var mProcessBackgroundColor = Color.parseColor("#50000000")
    // 进度条默认为白色
    private var mProcessColor = Color.parseColor("#FFFFFF")
    // 进度条宽度
    private var mProcessWidth = 10f
    // 文字颜色
    private var mTextColor = Color.parseColor("#FFFFFF")
    // 文字大小
    private var mTextSize = 20f
    // 倒计时总时间
    private var countDownTime = 5
    // 圆心X坐标
    private var centerX  = 0f
    // 圆心Y坐标
    private var centerY  = 0f
    // 圆的半径
    private var radius  = 0f
    // 当前进度角度
    private var currentAngle = 0f
    // 剩余时间
    private var remainingTime = countDownTime //剩余时间
    // 动画控制器
    private lateinit var animator: ValueAnimator
    // 倒计时结束监听器
    private var listener: CircleCountDownView.CountDownListener? = null
    private val sdf = SimpleDateFormat("mm分ss秒", Locale.getDefault())
    fun setCountDownTime(time: Int){
        countDownTime = time -1000
    }
    // 标记是否已完成倒计时
    var isFinish = false
    //背景画笔对象
    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE      // 描边
        strokeWidth = mProcessWidth     // 线宽
        color = mProcessBackgroundColor // 颜色
        strokeCap = Paint.Cap.ROUND     //两端弧度
    }
    //进度画笔对象
    private val processPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeWidth = mProcessWidth
        color = mProcessColor
        strokeCap = Paint.Cap.ROUND
        //渐变颜色
        shader = SweepGradient(centerX,centerY, intArrayOf(Color.RED,Color.YELLOW,Color.GREEN),null)

    }
    //文字画笔对象
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = mTextColor
        textSize = mTextSize
        textAlign = Paint.Align.CENTER
        typeface = Typeface.DEFAULT_BOLD
    }

    /**
     * 读取xml文件的属性值
     */
    fun setOnCountDownFinishListener(listener: CircleCountDownView.CountDownListener){
        this.listener = listener
    }


    /**
     * 大小发生变化
     */
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        centerX = w / 2f
        centerY = h / 2f
        radius = (w.coerceAtMost(h) - mProcessWidth) / 2f
    }
    //绘制UI
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // 绘制背景圆环
        canvas.drawCircle(centerX,centerX,radius,backgroundPaint)
        // 计算当前进度对应的角度
        val sweepAngle = 360 * (currentAngle/100f)
        // 绘制进度圆弧
        canvas.drawArc(
            centerX-radius,
            centerY-radius,
            centerX+radius,
            centerY+radius ,
            -90f,// 从顶部开始绘制
            sweepAngle,
            false,
            processPaint)
        // 计算文字绘制的Y坐标，使文字垂直居中
        val textY = centerY - ((textPaint.descent() + textPaint.ascent()) / 2)
        // 根据剩余时间显示不同的文字
        if(remainingTime>60000){
            canvas.drawText("${sdf.format(remainingTime)}后可抢",centerX,textY,textPaint)
        }else if(remainingTime in 1..59999) {
            textPaint.textSize = 50f
            // 1分钟内，显示剩余秒数
            canvas.drawText("${remainingTime / 1000}", centerX, textY, textPaint)
        }else {
            // 倒计时结束，显示"抢"字
            isFinish = true
            textPaint.textSize = 70f
            canvas.drawText("抢", centerX, textY, textPaint)
        }
    }

    /**
     * 开始倒计时
     */
    fun startCountDown(){
        // 创建从总时间到0的属性动画
        animator = ValueAnimator.ofInt(countDownTime, 0).apply {
            // 动画持续时间等于倒计时总时间
            duration = countDownTime.toLong()
            // 线性插值器，匀速变化
            interpolator = LinearInterpolator()
            // 添加动画更新监听器
            addUpdateListener {
                // 更新剩余时间
                remainingTime = it.animatedValue as Int
                // 计算当前进度（0-100）
                currentAngle = 100f - (remainingTime.toFloat() / countDownTime * 100f)
                // 重绘视图
                invalidate()
                //倒计时结束，回调监听器
                if (remainingTime == 0 && listener != null) {
                    listener?.onCountDownFinish()
                    isFinish = true
                }
            }
            //启动动画
            start()
        }
    }
    /**
     * 取消倒计时
     */
    fun cancelCountDown(){
        animator.cancel()
    }
    /**
     * 当视图从窗口移除时调用，用于清理资源
     */
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        // 取消动画，防止内存泄漏
        cancelCountDown()
    }

}